using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using System.ComponentModel;
using System.Windows.Threading;

namespace Ricciolo.PaperBoy.UI
{
    [Serializable]
    public abstract class NotifyObject : INotifyPropertyChanged, IDeserializationCallback
    {
        [NonSerialized]
        private PropertyChangedEventHandler propertyChanged;
        [NonSerialized]
        private Dispatcher _dispatcher;

        protected NotifyObject()
        {
            this._dispatcher = Dispatcher.CurrentDispatcher;
        }

        public Dispatcher Dispatcher
        {
            get { return _dispatcher; }
        }

        public bool CheckAccess()
        {
            bool flag = true;
            Dispatcher dispatcher = this._dispatcher;
            if (dispatcher != null)
            {
                flag = dispatcher.CheckAccess();
            }
            return flag;
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged
        {
            add { this.propertyChanged += value; }
            remove { propertyChanged -= value; }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (propertyChanged != null)
                if (this.CheckAccess())
                    this.propertyChanged(this, e);
                else
                    this.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, this.propertyChanged, this, e);
        }

        #endregion


        #region IDeserializationCallback Members

        ///<summary>
        ///Runs when the entire object graph has been deserialized.
        ///</summary>
        ///
        ///<param name="sender">The object that initiated the callback. The functionality for this parameter is not currently implemented. </param>
        void IDeserializationCallback.OnDeserialization(object sender)
        {
            this._dispatcher = Dispatcher.CurrentDispatcher;
        }

        #endregion
    }
}